package com.junchenrobot.mes.config;

import lombok.extern.slf4j.Slf4j;

import java.util.Map;
import java.util.concurrent.*;

@Slf4j
public class AsyncPool {
    
    private static final Map<String, ScheduledFuture<?>> map = new ConcurrentHashMap<>();
    
    private static final ScheduledExecutorService service = Executors.newScheduledThreadPool(100);
    
    
    private AsyncPool() {
    
    }
    
    public static void schedule(String key, Runnable runnable, int period, TimeUnit timeUnit) {
        ScheduledFuture<?> scheduledFuture = service.scheduleAtFixedRate(runnable, 0L, period, timeUnit);
        map.put(key, scheduledFuture);
        log.info("{}创建定时任务", key);
    }
    
    public static boolean cancel(String key) {
        boolean cancel = false;
        if (map.containsKey(key)) {
            ScheduledFuture<?> scheduledFuture = map.get(key);
            cancel = scheduledFuture.cancel(true);
            log.info("{}任务取消{}", key, cancel);
            if (cancel) {
                map.remove(key);
            }
        }
        return cancel;
    }
    
    public static boolean containsKey(String key) {
        return map.containsKey(key);
    }
    
}
